package com.huika.dealontop.control.login.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.event.CallMainPagerChangeEvent;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.DialogUtils;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.IOSAlertDialog;
import com.huika.dealontop.views.cleardit.ClearableEditText;
import com.huika.huikalib.utils.StringUtils;

import de.greenrobot.event.EventBus;

/**
 * Created by cailu on 2015/11/16.
 */
public class SuccessPageTwo extends BaseAct {

    private ClearableEditText etPhone;
    private String phone;
    private ClearableEditText etVerfy;
    private TextView btnVerfy;
    private Button mNextbt;
    private Button mCancelbt;
    private TextView mTvInformation;
    String mSuccessTwo;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_successpage_two);
    }


    @Override
    protected void initWidget() {
        super.initWidget();
        etPhone = (ClearableEditText) findViewById(R.id.et_pwd_asn);
        etVerfy = (ClearableEditText) findViewById(R.id.et_verfy_ar);
        mTvInformation = (TextView) findViewById(R.id.successpage_two_information);
        btnVerfy = (TextView) findViewById(R.id.btn_verfy_ar);
        mNextbt = (Button) findViewById(R.id.btn_asn);
        mCancelbt = (Button) findViewById(R.id.btn_cancel);
        initListener();
        //设置信息中的文字效果
        setInformation();
        //

        Intent intent = getIntent();

        mSuccessTwo = intent.getStringExtra("SuccessTwo");

    }

    private void setInformation() {
        String str1 = UIUtils.getString(R.string.register_successtwo_one);
        String str2 = UIUtils.getString(R.string.register_successtwo_two);
        String str3 = UIUtils.getString(R.string.register_successtwo_three);
        //设置高亮样式一
        SpannableString sp1 = new SpannableString(str1);
        SpannableString sp2 = new SpannableString(str2);
        SpannableString sp3 = new SpannableString(str3);
        sp1.setSpan(new ForegroundColorSpan(UIUtils.getColor(R.color.color_999999)), 0, str1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp3.setSpan(new ForegroundColorSpan(UIUtils.getColor(R.color.color_999999)), 0, str3.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp2.setSpan(new ForegroundColorSpan(UIUtils.getColor(R.color.color_fd702b)), 0, str2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        StringBuilder sb = new StringBuilder();
        sb.append(sp1).append(" ").append(sp2).append(" ").append(sp3);
        mTvInformation.setText(sp1);
        mTvInformation.append(" ");
        mTvInformation.append(sp2);
        mTvInformation.append(" ");
        mTvInformation.append(sp3);
    }

    private void initListener() {
        mCancelbt.setOnClickListener(this);
        mNextbt.setOnClickListener(this);
        etVerfy.setOnClickListener(this);
        btnVerfy.setOnClickListener(this);

    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);

        switch (v.getId()) {
            case R.id.btn_verfy_ar:
                verfyNet();
                break;
            case R.id.btn_asn:
                register();
                break;
            case R.id.btn_cancel:
                aty.finish();
                EventBus.getDefault().post(new CallMainPagerChangeEvent(1));
                break;

        }
    }

    private void verfyNet() {
        showLoadingDialog("");
        phone = getInputStr(etPhone);
        if (StringUtils.isEmpty(phone)) {
            showToastMsg(getString(R.string.register_illegalemptyphone));
            return;
        }
        if (!StringUtils.isTaiPhone(phone)) {
            showToastMsg(getString(R.string.register_illegalphone));
            return;
        }
        //获取验证码
        FormResultRequest request = new FormResultRequest(UrlConstants.GETSMSVERIFICATION, codeListener, this, new TypeToken<RequestResult>() {
        }.getType());
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();

        ajaxParams.putStringTypeParam("account", phone);
        //账号类型（1.手机号码 2.电子邮箱）
        ajaxParams.putCommonTypeParam("accType", Constants.AccountType.PHONE);
        //类型（注册1,找回密码2,修改密码3,优惠券4,商家审核短信下发5,快速登录6,订阅手机发送7,修改手机8,完善资料（邮箱注册添加手机号）9,修改邮箱10）
        ajaxParams.putCommonTypeParam("type", Constants.ValidateType.BOUND_PHONE);

        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);


        request.setRequestParams(ajaxParams);

        executeRequest(request);
        // }
    }

    private void register() {

        phone = getInputStr(etPhone);
        if (StringUtils.isEmpty(phone)) {
            showToastMsg(getString(R.string.register_illegalemptyphone));
            return;
        }
        if (!StringUtils.isTaiPhone(phone)) {
            showToastMsg(getString(R.string.register_illegalphone));
            return;
        }

        if (TextUtils.isEmpty(etVerfy.getText())) {
            showToastMsg(getString(R.string.register_empty_verfy));
            return;
        }
        showLoadingDialog("");
        //    /Member/MemberEmailInfoPerfect

        FormResultRequest request = new FormResultRequest(UrlConstants.MAILADDPHONE, successListener, this, new TypeToken<RequestResult<UserModel>>() {
        }.getType());
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();

//        userID
//                phone
//        validate
//                lang

        //账号（RSA加密）"0888123456"
        ajaxParams.putCommonTypeParam("userID", GlobalApp.getInstance().getUserId());
        //密码（MD5+RSA加密）
        ajaxParams.putStringTypeParam("phone", phone);
        //验证码
        ajaxParams.putStringTypeParam("validate", getInputStr(etVerfy));


        request.setRequestParams(ajaxParams);
        executeRequest(request);
        //}
    }


    private Response.Listener<RequestResult> codeListener = new Response.Listener<RequestResult>() {
        @Override
        public void onResponse(RequestResult arg0) {
            dismissLoadingDialog();
            showToastMsg(arg0.msg);
            btnVerfy.setClickable(false);
            setVerfyEt(true);
            new CountDownTimer(120000, 1000) {
                public void onTick(long millisUntilFinished) {
                    //btnVerfy.setTextColor(getResources().getColor(R.color.color_969696));
                    btnVerfy.setText(String.format("%s" + "S", String.valueOf(millisUntilFinished / 1000)));
                }

                public void onFinish() {
                    //btnVerfy.setTextColor(getResources().getColor(R.color.color_f25522));
                    btnVerfy.setText(R.string.register_getVerification);
                    btnVerfy.setClickable(true);
                }
            }.start();
        }
    };

    private Response.Listener<RequestResult> successListener = new Response.Listener<RequestResult>() {
        @Override
        public void onResponse(RequestResult arg0) {
            dismissLoadingDialog();
            //优惠券有效。
            if (mSuccessTwo.equals("1")) {
                //EventBus.getDefault().post(new CallMainPagerChangeEvent(1));
                //判断推荐码是否正确，然后弹出是否给予恭喜菜单。
                IOSAlertDialog dialog = DialogUtils.getInstance().createTitleDialog(SuccessPageTwo.this, getString(R.string.register_successpagetwo_dialog));
                dialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        aty.finish();
                        // showToastMsg(getString(R.string.register_successpagetwo_dialog));
                    }
                });
                dialog.setCancelable(false);
                dialog.show();

            } else {
                aty.finish();
            }

            //注册成功,然后会进入另一个窗口,不会弹吐司了.
            // showToastMsg(arg0.msg);
            // aty.finish();


        }
    };

    private void setVerfyEt(boolean isShow) {
        if (isShow) {
            etVerfy.setEnabled(true);
        } else {
            etVerfy.setEnabled(false);
        }
    }

}
